"use strict";
const semver = require("semver");
const colors = require("colors");
const log = require("@yk-cli-dev/log");

const LOWEST_NODE_VERSION = "17.0.0";
class Command {
  constructor(args) {
    if (!args) {
      throw new Error("参数不能为空！");
    }
    if (!Array.isArray(args)) {
      throw new Error("参数必须为数组！");
    }
    if (args.length < 1) {
      throw new Error("参数列表不能为空！");
    }
    this._argv = args;
    let runner = new Promise((resolve, reject) => {
      let chain = Promise.resolve();
      chain = chain.then(() => this.checkNodeVersion());
      chain = chain.then(() => this.initArgs());
      chain = chain.then(() => this.init());
      chain = chain.then(() => this.exec());
      chain.catch((err) => {
        log.error(err);
      });
    });
  }
  init() {
    throw new Error("init必须实现");
  }
  exec() {
    throw new Error("init必须实现");
  }
  //检查node版本
  checkNodeVersion() {
    const currentVersion = process.version;
    const lowestVersion = LOWEST_NODE_VERSION;
    if (!semver.gte(currentVersion, lowestVersion)) {
      throw new Error(
        colors.red(
          `yk-cli-dev 需要安装 v${lowestVersion} 以上版本的 node 当前版本为${currentVersion}`
        )
      );
    }
  }
  initArgs() {
    this._cmd = this._argv[this._argv.length - 1];
    this._argv = this._argv.slice(0, this._argv.length - 1);
  }
}

module.exports = Command;
